﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Menu;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Menu
{
    public class UpdateMenuHandler : IRequestHandler<UpdateMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public UpdateMenuHandler(IBaseRepository<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var menu = menuRepo.GetAll().Where(x => x.MenuName == request.MenuName && x.IsDelete == false && x.Pid == request.Pid && x.Id!=request.Id).FirstOrDefault();
            if (menu!=null)
            {
                res.Code = ApiEnum.Error;
                res.Msg = "同一级菜单下不允许名称重复";
                return Task.FromResult(res);
            }
           
                menu = mapper.Map(request, menu);
                menu.UpdateName = "李四";
                menu.UpdateTime = DateTime.Now;
                menu.CreateTime = DateTime.Now;
                menu.CreateName = "张三";
                var r=menuRepo.Update(menu);
                if (r>0)
                {
                    res.Msg = "修改成功";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "修改失败";
                    res.Data = r;
                    res.Code = ApiEnum.Success;
                }
                return Task.FromResult(res);    
            
        }
    }
}
